import { PageDto } from "../../../models/page.model";
import { UaVideoEntity, UaVideoSearchDto, VideoTypeMap } from "../../../models/ua-card.model";
import { GlobalService } from "../../../services/global.service";
import { LocalStorage } from "../../../services/local-storage.service";
import { UaVideoService } from "../../../services/ua-video.service";
import { formatTime } from "../../../utils/util";

// pages/video/user-video-list/user-video-list.page.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CDN_HOST: GlobalService.CDN_HOST,
    videoList: [] as UaVideoEntity[],
    VideoTypeMap: VideoTypeMap,
    fab: {
      theme: 'danger'
    },
  },

  customData: {
    page: 1,
    totalPage: 1,
    searchRequest: {} as UaVideoSearchDto
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.setNavigationBarTitle({
      title: '我的B站投稿'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.customData.page = 1;
    this.load();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.customData.page = 1;
    this.load();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (this.customData.page + 1 > this.customData.totalPage) {
      return;
    }
    this.customData.page++;
    this.load();
  },

  load() {
    const search = { userId: LocalStorage.getUserInfo()?.id };
    Object.assign(search, this.customData.searchRequest)
    UaVideoService.searchWithPage(search, this.customData.page).then((response: PageDto<UaVideoEntity>) => {
      this.customData.totalPage = response.meta!.pageCount!;
      for (const item of response.data ?? []) {
        const date = new Date(item.uploadDate ?? Date.now());
        item.uploadDateStr = formatTime(date);
      }
      if (this.customData.page === 1) {
        this.setData({
          videoList: response.data
        })
      } else {
        this.setData({
          videoList: [...this.data.videoList, ...response.data!]
        })
      }
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onChoose(e: any) {
    wx.navigateTo({
      url: `/pages/video/user-video-edit/user-video-edit.page?videoId=${e.currentTarget.dataset['id']}`,
    });
  },

  onDelete(e: any) {
    const index = e.currentTarget.dataset.index;
    const trade = this.data.videoList[index];
    wx.showModal({
      title: '是否删除？',
      confirmText: "删除",
      cancelText: "取消",
      showCancel: true,
      confirmColor: "#eb445a",
      success: (res) => {
        if (res.confirm) {
          this.removeVideo(trade);
        }
      }
    });
  },

  removeVideo(trade: UaVideoEntity) {
    UaVideoService.removeById(trade.id!).then(() => {
      this.onShow();
    })
  },

  add() {
    wx.navigateTo({
      url: `/pages/video/user-video-edit/user-video-edit.page`,
    });
  }
})